import os
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
import requests
from importlib import import_module

COMMON_PATH = os.environ["COMMON_PATH"]
printer = import_module("printer").IndentPrinter(indent=3)

USERNAME = "dwzengzhiyong2"
PASSWORD = "Gmcc202505*"


def encrypted(pwd, browser):
    try:
        js_file_path = os.path.join(COMMON_PATH, "js", "sso", "sso.js")
        with open(js_file_path, "r", encoding="utf-8") as f:
            js_code = f.read()
        browser.evaluate_javascript("body", js_code)
        return browser.evaluate_javascript("body", f"encrypted('{pwd}');")
    except Exception as e:
        printer(f"[发生错误] 加密密码: {e}")
        raise e


def login(
    browser,
    client_id: str,
    return_url: str,
    usr: str = USERNAME,
    pwd: str = PASSWORD,
):

    printer("[sso登录] 加密密码")
    encrypted_pwd = encrypted(pwd, browser)
    username = "user:" + usr
    try:
        headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0"
        }
        login_url = f"http://sso.gmcc.net/sso/oauth/token?username={username}&password={encrypted_pwd}&grant_type=password&client_id={client_id}"
        response_auth = requests.post(login_url, json=None, headers=headers)
        response_auth.raise_for_status()
        token_data = response_auth.json()
        access_token = token_data["access_token"]
        refresh_token = token_data["refresh_token"]
        # 构造Return URL
        parsed = urlparse(return_url)
        query = parse_qs(parsed.query)
        query.update({"access_token": [access_token], "refresh_token": [refresh_token]})
        return urlunparse(parsed._replace(query=urlencode(query, doseq=True)))
    except Exception as e:
        printer(f"[发生错误] 登录授权: {e}")
        raise e
